package com.leyou.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.scheduled.AppTokenScheduled;
import com.sun.deploy.nativesandbox.comm.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 设置最大访问量
     */
    private Integer visit=1;
    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private AppTokenScheduled appTokenScheduled;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain ) {
        //获取request域
        ServerHttpRequest request = exchange.getRequest();
        //获取response域
        ServerHttpResponse response = exchange.getResponse();
        //给请求添加请求头
        request.mutate().header(LyConstants.APP_TOKEN_HEADER, appTokenScheduled.getToken()).build();
        //获取当前请求的url地址
        String url = request.getPath().toString();
        //判断当前url地址是否在白名单，白名单表示不需要登录就可以访问的
        if(isAllowPath(url)){
            //放行，继续执行其他过滤器或者微服务
            return chain.filter(exchange);
        }
        //获取cookie
        String token = null;
        //解析token
        Payload<UserInfo> payload = null;
        try {
            token = request.getCookies().getFirst(jwtProp.getCookie().getCookieName()).getValue();
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            //阻断继续访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
    }
        //得到用户id
        Long userId = payload.getUserInfo().getId();
        if(url.equals("/api/order")){
            //判断有没有访问入口的资格     限时
        if (!appTokenScheduled.isUserLoginBool()){
            //没有访问资格的直接拦截
            throw new LyException(503,"TIME_FAIL");
        }
            //判断用户有没有访问资格      限流
            if (!visitBoolean(userId)){
                //没有访问资格的直接拦截
               throw new LyException(503,"USER_FAIL");
            }
        }
        //将用户id放入请求头中
        request.mutate().header(LyConstants.USER_HOLDER_KEY, userId.toString()).build();
        //放行，继续执行其他过滤器或者微服务
        return chain.filter(exchange);
    }

    private boolean isAllowPath(String url) {
        //获取所有白名单路径
        List<String> allowPaths = filterProp.getAllowPaths();
        //查看当前的访问url地址是否包含于白名单集合中
        for (String allowPath : allowPaths) {
            if(url.contains(allowPath)){
                return true;
            }
        }
        return false;
    }
    private boolean visitBoolean(Long userId){
        //根据用户id获取redis的值
        String str = redisTemplate.opsForValue().get(userId.toString());
        //如果值是null，就把用户存进redis中,两小时失效
        if(str!=null){
            //有访问者的数据，直接返回true，但访问次数不自增
            return true;
        }else if (visit>1){
            //如果访问次数超过100，直接返回false
            return false;
        }
        else if (str==null){
            //把用户id存进redis中，有效期为2小时
            redisTemplate.opsForValue().set(userId.toString(),"我很随便的哟",2, TimeUnit.HOURS);
            //访问次数加1
            visit++;
        }else {
            return true;
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
